/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.factory.server.consumers;

import com.factory.server.bo.AbstractBusinessObject;
import com.factory.server.bo.ResultData;
import com.factory.server.cache.OutputCache;
import com.factory.server.scheduler.SchedulerServiceIface;
import com.factory.server.service.DataServiceIface;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 *Stores result to DB
 * @author milos
 */
@Component
@Scope("prototype")
public class ResultSaver implements Runnable {

    static final Logger LOG = Logger.getLogger(Consumer.class.getName());
    private ResultQueue resultQueue;

    public ResultSaver() {
    }
    @Autowired
    private SchedulerServiceIface schedulerService;
    @Autowired
    private DataServiceIface dataService;

    public void run() {

        while (true) { //TODO dorobit vypinaci signal
            AbstractBusinessObject result = schedulerService.getResultQueue().get();
            if (result != null) {
                dataService.store(result);
            }
//            if (result instanceof Prime) {
//                OutputCache.primes.remove(((Prime)result).getValue());
//            }
            if (result instanceof ResultData) {
                if (OutputCache.get(((ResultData) result).getInputId()) != null) {
                    OutputCache.remove(((ResultData) result).getInputId());
                }
            }
        }
    }

    public ResultQueue getResultQueue() {
        return resultQueue;
    }

    public void setResultQueue(ResultQueue resultQueue) {
        this.resultQueue = resultQueue;
    }
}
